//
//  SearchViewController.m
//  News
//
//  Created by lanou3g on 15/7/20.
//  Copyright (c) 2015年 蓝欧科技. All rights reserved.
//

#import "SearchViewController.h"
#import "AFNetworking.h"
#import "RequestData.h"//自己封装的请求数据类，里面用了AFNetworking
#import "HotWordsModel.h"//近期热词的model类
#import "HotWordsCollectionViewCell.h"
#import "SearchBackModel.h"//搜索之后返回的数据的model类
#import "CommonFunc.h"//导入将字符串转为base64格式字符串的工具类，点键盘的搜索返回数据的接口需要用
#import "SearchDetailViewController.h"//导入搜索之后点cell出现的详情页的控制器
#import "SearchBackOnlyTextCell.h"
#import "SearchBackImageCell.h"


@interface SearchViewController ()<UISearchBarDelegate,RequestFinish,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UISearchBar *searchBar;

@property (nonatomic,strong) UILabel *hotWordsLabel;

@property (nonatomic,retain) RequestData *request;
//作为collectionView（用来显示近期热词）的数据源
@property (nonatomic,retain) NSMutableArray *collectionViewDataArray;
//作为tableView（用来显示点击搜索之后出现的数据）的数据源
@property (nonatomic,retain) NSMutableArray *dataArray;

@property (nonatomic,retain) UICollectionView *collectionView;

@property (nonatomic,retain) UITableView *tableView;

@property (nonatomic,retain) SearchBackModel *searchBackModel;


@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    设置搜索控制器的根视图的背景颜色
    self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];
    //    设置导航栏标题
    self.navigationItem.title=@"搜索新闻";
    
//    添加点击搜索后出现的视图
    [self addSearchView];
    
//    下面两行代码用来请求“近期热词”需要的数据
    self.request=[RequestData shareRequestData];
    
    [self.request requestWithUrl:@"http://c.3g.163.com/nc/search/hotWord.html" delegate:self];

    self.dataArray=[NSMutableArray array];
    
    self.collectionViewDataArray=[NSMutableArray array];

}

//添加点击搜索后出现的视图到self.view的方法
-(void)addSearchView{
    
    //    创建搜索栏，并把它加到根视图上，这样才能显示
    self.searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(10, 80, 355, 30)];
    [self.view addSubview:_searchBar];
    
    //    设置搜索栏的属性,后面加空格是为了使它和下面“近期热词”对齐
    _searchBar.placeholder=@"请输入关键字...                                                    ";
    //    使搜索栏边框圆滑
    _searchBar.layer.cornerRadius = 3;
    _searchBar.delegate=self;
    //        //    设置搜索栏的代理
    //        _searchBar.delegate=self;
    //    下面三行代码用于去除搜索栏周围的灰色，提升用户体验
    _searchBar.layer.masksToBounds = YES;
    [_searchBar.layer setBorderWidth:8];
    [_searchBar.layer setBorderColor:[UIColor whiteColor].CGColor];
    
    //    创建近期热词的显示Label
    self.hotWordsLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 120, 355, 30)];
    [self.view addSubview:_hotWordsLabel];
    //    前面加空格是为了使它和上面“请输入关键字”对齐
    _hotWordsLabel.text=@"        近期热词";
    _hotWordsLabel.layer.cornerRadius=3;
    _hotWordsLabel.layer.masksToBounds=YES;
    //    左对齐
    _hotWordsLabel.textAlignment=NSTextAlignmentLeft;
    //    字体
    _hotWordsLabel.font=[UIFont systemFontOfSize:12];
    //    背景颜色
    _hotWordsLabel.backgroundColor=[UIColor whiteColor];

    
}

#pragma mark - 搜索栏的代理方法 -
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
//    用第三方工具类将关键字用base64编码，接口需要这样
    NSString *str=[CommonFunc base64StringFromText:searchBar.text];
    
    NSString *string=[NSString stringWithFormat:@"http://c.3g.163.com/search/doc/MA%@3D%@3D/20/%@.html",@"%",@"%",str];
    
    [self.request requestWithUrl:string delegate:self];
    
//    创建tableView，用来显示搜索得到的数据
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(10, 120, 355, self.view.bounds.size.height) style:UITableViewStylePlain];
//    设置代理
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.view addSubview:self.tableView];
}



#pragma mark - 请求数据完成的代理方法 -

-(void)requestSuccess:(id)responseObject{
    
//    如果[responseObject objectForKey:@"hotWordList"]有值，说明是近期热词的数据，进入if执行代码
    if ([responseObject objectForKey:@"hotWordList"]) {
        for (NSDictionary *dic in [responseObject objectForKey:@"hotWordList"]) {
            
            HotWordsModel *hotWordsModel=[[HotWordsModel alloc]init];
            
            hotWordsModel.hotWord=[dic objectForKey:@"hotWord"];
            
            [self.collectionViewDataArray addObject:hotWordsModel];
            
        }
        
        //    创建FlowLayout
        UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
        //    设置行之间的最小间隔
        layout.minimumLineSpacing=0;
        //    设置列之间的最小间隔
        layout.minimumInteritemSpacing=0;
        //    设置item(cell)的大小
        layout.itemSize=CGSizeMake(177.5, 30);
        
//        请求成功之后才会显示近期热词，所以在这里创建collectionView
        self.collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(10, 150, 355, [self.collectionViewDataArray count]/2*30) collectionViewLayout:layout];
        
        //    注册cell,CollectionViewCell上面只有一个子视图是contentView，不像tableViewCell一样有四种样式，所以使用时必须自定义
        [self.collectionView registerClass:[HotWordsCollectionViewCell class] forCellWithReuseIdentifier:@"hotWordsCell"];
        
//        设置代理
        self.collectionView.delegate=self;
        self.collectionView.dataSource=self;
//        使边角圆滑
        self.collectionView.layer.cornerRadius=3;
        self.collectionView.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:self.collectionView];
        
        //    在中间加一个白色的视图，显得上面和下面的视图是一体
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(10, 145, 355, 10)];
        view.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:view];
        
//        数据源（self.collectionViewDataArray）有变化需要重新加载数据
        [self.collectionView reloadData];
        
    }
    
//    如果[responseObject objectForKey:@"result"]有值，说明是搜索得到的数据，进入if执行代码，需要展示在tableView上面
    if ([responseObject objectForKey:@"result"]) {
        
        [self.dataArray removeAllObjects];
        for (NSDictionary *dic in [responseObject objectForKey:@"result"]) {
            
            SearchBackModel *searchBackModel=[[SearchBackModel alloc]init];
            
            searchBackModel.title=[dic objectForKey:@"title"];
            searchBackModel.ID=[dic objectForKey:@"id"];
            searchBackModel.ptime=[dic objectForKey:@"ptime"];
            searchBackModel.imageUrlString=[dic objectForKey:@"url"];
            
            [self.dataArray addObject:searchBackModel];
            
            
        }
        [self.tableView reloadData];
    }
    
}

//请求出现错误执行的方法
-(void)requestError:(NSError *)error{
    
    NSLog(@"error=%@",error);
}

#pragma mark - tableView的代理方法 -

//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SearchBackModel *searchBackModel=[self.dataArray objectAtIndex:indexPath.row];
    
    CGFloat height=[SearchBackModel stringHeight:searchBackModel.title];
    
    return height+35;
}

//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *textIdentifier=@"textCell";
    static NSString *imageIdentifier=@"imageCell";
    
//    给searchBackModel添加观察者后，返回主界面时会出现类似野指针的问题，所有这里用属性
    self.searchBackModel=[self.dataArray objectAtIndex:indexPath.row];
    
//    如果model类的对象有imageUrlString，说明cell有图片，执行if里面代码
    if (self.searchBackModel.imageUrlString.length>0) {
        
        SearchBackImageCell *cell=[tableView dequeueReusableCellWithIdentifier:imageIdentifier];
        
        if (!cell) {
            cell=[[SearchBackImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:imageIdentifier];
        }
        
//        执行cell里面的-(void)setSearchBackModel:(SearchBackModel *)searchBackModel方法，给cell赋值
        cell.searchBackModel=self.searchBackModel;
        
        if (self.searchBackModel.image) {
            cell.leftImageView.image=self.searchBackModel.image;
        }else{
            cell.leftImageView.image=[UIImage imageNamed:@"picholder.png"];
            
            [self.searchBackModel addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:(__bridge void *)(indexPath)];
            
            [self.searchBackModel startDownImage];
            
            
        }
         
        return cell;
        
        
    }else{//如果model类的对象的imageUrlString为空，说明cell没有图片，执行else里面代码
    
    SearchBackOnlyTextCell *cell=[tableView dequeueReusableCellWithIdentifier:textIdentifier];
    
    if (!cell) {
        cell=[[SearchBackOnlyTextCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:textIdentifier];
    }
    
    cell.searchBackModel=self.searchBackModel;
        
        return cell;
    }

    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    SearchBackImageCell *cell=(SearchBackImageCell *)[self.tableView cellForRowAtIndexPath:(__bridge NSIndexPath *)context];
    
    cell.leftImageView.image=[change objectForKey:@"new"];
    
    
    [object removeObserver:self forKeyPath:@"image"];
    
}

//选中某一行执行的方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SearchDetailViewController *searchDetailVC=[[SearchDetailViewController alloc]init];
    
    SearchBackModel *searchBackModel=[self.dataArray objectAtIndex:indexPath.row];
    
    [self.view endEditing:YES];
    
//    从前往后传值，用属性
    searchDetailVC.ID=searchBackModel.ID;
    
    [self.navigationController pushViewController:searchDetailVC animated:YES];
}



#pragma mark - collectionView的代理方法 -
//cell的数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return [self.collectionViewDataArray count];
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    在上面已经注册过了
    HotWordsCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"hotWordsCell" forIndexPath:indexPath];
    
    HotWordsModel *hotWordsModel=[self.collectionViewDataArray objectAtIndex:indexPath.row];
    cell.hotWordsLabel.text=hotWordsModel.hotWord;
    cell.hotWordsLabel.font=[UIFont systemFontOfSize:14];
    
    
    return cell;
}

//选中某一个cell执行的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    获取到选中的cell，[collectionView subviews]能获取到所有的cell,它返回一个数组
    HotWordsCollectionViewCell *cell=[[collectionView subviews] objectAtIndex:indexPath.item];
//    把点击的cell的文字赋值给searchBar
    self.searchBar.text=cell.hotWordsLabel.text;
    
    [self searchBarSearchButtonClicked:self.searchBar];
}





//这个方法实现点击空白区域回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
